package 数据结构OJ;

public class 相交链表_09 {

    public class ListNode {
        int val;
        ListNode next;

        ListNode(int x) {
            val = x;
        }
    }

    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        if (headA == null || headB == null) {
            return null;
        }
        int lengthA = 0, lengthB = 0;
        ListNode i = headA;
        ListNode j = headB;
        //求出A长B的长度
        while (i != null) {
            i = i.next;
            lengthA++;
        }
        while (j != null) {
            j = j.next;
            lengthB++;
        }
        //使A和B的还未相交的长度相等
        while (lengthB > lengthA) {
            headB = headB.next;
            lengthB--;
        }
        while (lengthB < lengthA) {
            headA = headA.next;
            lengthA--;
        }
        //遍历链表A或B，如果相同的第N个节点相等时，则该点为相交交点
        //如果遍历结束，未找到匹配节点，返回null
        while (headA != null) {
            if (headA == headB)
                return headA;
            headA = headA.next;
            headB = headB.next;
        }

        return null;
    }
}


//           if(headA == null || headB == null)
//            return null;
//    ListNode a = headA;
//    ListNode b = headB;
//        while(a != b) {
//        if(a != null){
//            a = a.next;
//        }else{
//            a = headB;
//        }
//        if(b != null) {
//            b = b.next;
//        }else {
//            b = headA;
//        }
//    }
//        return headA;

